package com.jiechuang.user.controller;



import com.jiechuang.common.bean.User;
import com.jiechuang.common.util.JWTUtil;
import com.jiechuang.common.web.Code;
import com.jiechuang.common.web.Response;
import com.jiechuang.user.dto.LoginInfo;
import com.jiechuang.user.remote.OrderServer;
import com.jiechuang.user.service.LoginService;
import com.jiechuang.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.stream.Collectors;

@RefreshScope
@RestController
public class LoginController {
    @Autowired
    private OrderServer orderServer;
    @Autowired
    private LoginService loginService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private JWTUtil jwtUtil;
    @RequestMapping(method = RequestMethod.POST, value = "login")
    public Response login(@RequestBody LoginInfo loginInfo) {
        try {
            User user = loginService.login(loginInfo.getUsername(), loginInfo.getPassword());
            if(user!=null){
                String token = jwtUtil.createJWT(user.getId()+"", user.getUsername(), user.getRoleList().stream().map(a->{return a.getRoleCode();}).collect(Collectors.toList()));
                return new Response(Code.LOGIN_SUCCESS, token);
            }
            return new Response(Code.USERNAMEORPASSWORD_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(Code.LOGIN_ERROR);
        }
    }
}
